﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarvellousWorks.PracticalPatternNet8.SignletonPattern.SignletonN;

public class WorkItemCollection<T> where T : class,IWorkItem
{
    // 定义最多保存的实例数量N
    protected int _max;
    protected IList<T> workItems = new List<T>();
    public WorkItemCollection(int max)
    {
        _max = max;
    }

    /// <summary>
    /// 外部获取 T 实例的入口
    /// </summary>
    /// <returns></returns>
    public virtual T? GetWorkItem()
    {
        if (workItems == null || workItems.Count == 0) return null;
        // 对外反馈一个现成的实例
        foreach (var item in workItems)
        {
            if (item.Status == Status.Free)
            {
                item.Status = Status.Busy;
                return item;
            }
        }
        return null; // 虽然有现成的实例，但是都处于忙碌状态 所以返回null
    }

    /// <summary>
    /// 新增一个类型
    /// </summary>
    /// <param name="item"></param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <exception cref="OverflowException"></exception>
    public virtual void Add(T? item)
    {
        if(item==null) throw new ArgumentNullException("item");
        if (!CouldAddNewInstance) throw new OverflowException();
        item.Status = Status.Free;
        workItems.Add(item);
    }

    /// <summary>
    /// 判断是否可以增加新的实例
    /// </summary>
    public virtual bool CouldAddNewInstance {  
        get { return workItems.Count<_max; } 
    }
}
